package com.book.settings.service.impl;

import com.book.common.Result;
import com.book.common.UUidUtil;
import com.book.settings.mapper.UserMapper;
import com.book.settings.pojo.User;
import com.book.settings.service.UserService;
import com.book.workbench.mapper.BookMapper;
import com.book.workbench.pojo.Book;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BookMapper bookMapper;

    @Override
    public Integer addUser(User user) {
        User user1 = userMapper.getUserByAct(user.getAct());
        if(user1==null){
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String nowDate = dateFormat.format(date);
            user.setRegdate(nowDate);
            user.setId(UUidUtil.getUUID());
            return userMapper.addUser(user);
        }else{
            return -1;
        }
    }

    @Override
    public PageInfo<User> getListUser(User user) {
        PageHelper.startPage(user.getPageNo(),user.getPageSize());
        List<User> users = userMapper.getListUser(user);
        PageInfo<User> page = new PageInfo<>(users,user.getPageSize());
        return page;
    }

    @Override
    public Integer getCountListUser(User user) {
        return userMapper.getCountListUser(user);
    }

    @Override
    public Integer deleteUserById(User user) {
        int deleteUserResult;
        User user1 = userMapper.searchUserById(user.getId());
        List<Book> books = bookMapper.searchUserNotReturnBook(user1.getAct());
        if(books==null){
            deleteUserResult = userMapper.deleteUserById(user);
        }else{
            deleteUserResult = -1;
        }
        return deleteUserResult;
    }

    @Override
    public Integer updateUserById(User user) {
        int updateUserResult = userMapper.updateUserById(user);
        return updateUserResult;
    }

    @Override
    public PageInfo<User> getListALlUser(User user) {
        PageHelper.startPage(user.getPageNo(),user.getPageSize());
        List<User> users = userMapper.getListAllUser(user);
        PageInfo<User> page = new PageInfo<>(users,user.getPageSize());
        return page;
    }

    @Override
    public Integer getCountListAllUser(User user) {
        return userMapper.getCountListAllUser(user);
    }

    @Override
    public User searchUserById(String id) {
        return userMapper.searchUserById(id);
    }

    @Override
    public User searchUserByAct(String act) {
        return userMapper.getUserByAct(act);
    }
}
